<?php

class CatalogController extends Controller
{
	public $baseUrl;
	public $isCatalog;
	public $login;
	public $title, $categories;

	public function init() {
		$this->baseUrl = Yii::app()->request->baseUrl;
		$this->isCatalog = true;
		$session = new CHttpSession;
		$session->open();
		$this->login = $session['login'];
		$session->close();

		$this->title = 'Каталог';
		$this->categories = array(
			'index' => array('title' => 'Товары', 'url' => CHtml::normalizeUrl(array('catalog/'))),
			'news' => array('title' => 'Новости', 'url' => CHtml::normalizeUrl(array('catalog/news'))),
			'actions' => array('title' => 'Акции', 'url' => CHtml::normalizeUrl(array('catalog/actions'))),
			'gallery' => array('title' => 'Фотогалерея', 'url' => CHtml::normalizeUrl(array('catalog/gallery'))),
			'video_gallery' => array('title' => 'Видеогалерея', 'url' => CHtml::normalizeUrl(array('catalog/video')))

		);
	}

	//region Управление Вилеогалерея
	public function actionVideo()
	{
		$this->categories['video_gallery']['active'] = true;
		$data['items']=VideoGallery::model()->findAll();
		$this->render('video/all', $data);
	}

	public function actionControlVideo()
	{
		$data=array();
		if(Yii::app()->getRequest()->getQuery('id')){
			$data['item']=VideoGallery::model()->findByPk(Yii::app()->getRequest()->getQuery('id'));
		}
		$this->renderPartial('video/control',$data);
	}
	public function actionSaveVideo()
	{
		if(Yii::app()->getRequest()->getQuery('id') == 'new')
			$record = new VideoGallery();
		else $record = VideoGallery::model()->findByPk(Yii::app()->getRequest()->getQuery('id'));
		$item_record=Yii::app()->getRequest()->getPost('item');
		$record->attributes=$item_record;
		$record->save();
		$this->redirect(CHtml::normalizeUrl(array('catalog/video')));
	}

	public function actionDeletedVideo($id)
	{
		VideoGallery::model()->deleteByPk($id);
		$this->redirect(CHtml::normalizeUrl(array('catalog/video')));
	}
	//endregion
	//region Управление Фотогалереей
	public function actionGallery()
	{
		$this->categories['gallery']['active'] = true;
		$data['items']=Gallery::model()->findAll();
		$this->render('gallery/all', $data);
	}

	public function actionControlGallery()
	{
		$data=array();
		if(Yii::app()->getRequest()->getQuery('id')){
			$data['item']=Gallery::model()->findByPk(Yii::app()->getRequest()->getQuery('id'));
		}
		$this->renderPartial('gallery/control',$data);
	}

	public function actionSaveGallery()
	{
		if(Yii::app()->getRequest()->getQuery('id') == 'new')
			$record = new Gallery();
		else $record = Gallery::model()->findByPk(Yii::app()->getRequest()->getQuery('id'));
		$item_record=Yii::app()->getRequest()->getPost('item');
		$record->attributes=$item_record;
		$record->save();
		if(Yii::app()->getRequest()->getPost('images')){
			$images=Yii::app()->getRequest()->getPost('images');
			$edit_img=Yii::app()->getRequest()->getPost('edit_img');

			foreach ($images as $key=>$value) {
				if(is_int($key)){
					Yii2Debug::dump($value);
					if($edit_img[$key]){
						$img_record=GalleryImg::model()->findByPk($key);
						$img_record->title=$value->title;
						$img_record->id_gallery=$record->id;
						$img_record->save();
					}
				}else{
					$img_record=new GalleryImg();
					$img_record->attributes=$value;
					$img_record->id_gallery=$record->id;
					$img_record->save();
				}
			}
			if (preg_match('/,/ui',Yii::app()->getRequest()->getPost('is_deleted')) && Yii::app()->getRequest()->getPost('is_deleted')) {
				$is_deleted = explode(',', Yii::app()->getRequest()->getPost('is_deleted'));
			} else {
				$is_deleted[0]=Yii::app()->getRequest()->getPost('is_deleted');
			}
			foreach($is_deleted as $del){
				if ($del) {
					if (is_numeric($del)) {
						GalleryImg::model()->deleteByPk($del);
						if (file_exists(YiiBase::getPathOfAlias('webroot') . $images[$del]['img'])) {
							@unlink(YiiBase::getPathOfAlias('webroot') . $images[$del]['img']);
						}
					} else {
						if (file_exists(YiiBase::getPathOfAlias('webroot') . $images[$del]['img'])) {
							@unlink(YiiBase::getPathOfAlias('webroot') . $images[$del]['img']);
						}
					}
				}
			}
		}
		$this->redirect(CHtml::normalizeUrl(array('catalog/gallery')));
	}
	public function actionDeletedGallery($id)
	{
		$deleted=Gallery::model()->findByPk($id);
		foreach ($deleted->galleryImgs as $del_img) {
			if (file_exists(YiiBase::getPathOfAlias('webroot') . $del_img->img)) {
				@unlink(YiiBase::getPathOfAlias('webroot') . $del_img->img);
			}
		}
		$deleted->delete();
		$this->redirect(CHtml::normalizeUrl(array('catalog/gallery')));
	}
	//endregion
	//region Управление акции
	public function actionActions()
	{
		$this->categories['actions']['active'] = true;
		$data['actions']= Actions::model()->findAll();
		$this->render('actions/all', $data);
	}

	public function actionEditAction()
	{
		$data=array();
		if(Yii::app()->getRequest()->getQuery('id')){
			$data['item']=Actions::model()->multilang()->findByPk(Yii::app()->getRequest()->getQuery('id'));
		}
		$this->renderPartial('actions/edit',$data);
	}
	public function actionSaveAction()
	{
		if(Yii::app()->getRequest()->getQuery('id') == 'new')
			$record = new Actions();
		else $record = Actions::model()->multilang()->findByPk(Yii::app()->getRequest()->getQuery('id'));
		$item_record=Yii::app()->getRequest()->getPost('item');
		$record->attributes=$item_record;
		$record->save();
		$this->redirect(CHtml::normalizeUrl(array('catalog/actions')));
	}
	public function actionDeletedAction($id)
	{
		$deleted=Actions::model()->findByPk($id);
		if(file_exists(YiiBase::getPathOfAlias('webroot').$deleted->img)){
			@unlink(YiiBase::getPathOfAlias('webroot').$deleted->img);
		}
		$deleted->delete();
		$this->redirect(CHtml::normalizeUrl(array('catalog/actions')));
	}
	//endregion
	//region Управление новостями
	public function actionNews()
	{
		$this->categories['news']['active'] = true;
		$data['items'] =News::model()->findAll();
		$this->render('news/all', $data);
	}

	public function actionControlNew()
	{
		if(Yii::app()->getRequest()->getQuery('id')){
			$data['item']=News::model()->multilang()->findByPk(Yii::app()->getRequest()->getQuery('id'));
		}else{
			$data=array();
		}
		$this->renderPartial('news/view',$data);
	}

	public function actionSaveNew($id)
	{
		$item = Yii::app()->getRequest()->getPost('item');
		if( $id == 'new' ) {
			$record = new News();
			//$record = $record->multilang();
		} else {
			$record = News::model()->multilang()->findByPk($id);
			if ($record->img!=$item['img']) {
				$deleted_img= YiiBase::getPathOfAlias('webroot').$record->img;
			}
		}
		$record->attributes = $item;
		if( !$record->save() ) {
			$file_path = YiiBase::getPathOfAlias('webroot').$item['img'];
			if( file_exists( $file_path ) ) {
				unlink( $file_path );
			}
		}else{
			if(isset($deleted_img)){
				if( file_exists( $deleted_img ) ) {
					unlink( $deleted_img );
				}
			}
		}
		$this->redirect(CHtml::normalizeUrl(array('catalog/news')));
	}
	public function actionDeletedNew($id)
	{
		$deleted=Sliders::model()->findByPk($id);
		if( file_exists( YiiBase::getPathOfAlias('webroot').$deleted->img ) ) {
			unlink( YiiBase::getPathOfAlias('webroot').$deleted->img );
		}
		$deleted->delete();
		$this->redirect(CHtml::normalizeUrl(array('catalog/news')));
	}
	//endregion
	public function actionIndex() {
		$this->categories['index']['active'] = true;
		$data['categories'] = Category::model()->localized('ru')->findAll(array('order'=>'t.`level` ASC, t.`order` ASC'));
		$this->render('catalog', $data);
	}
	public function actionShow() {
		$ttt = Category::model()->multilang()->findAllByAttributes(array('id'=>19));
		$ttt = Category::model()->localized('en')->findAllByAttributes(array('id'=>19));
	}
	//region Управление меню
	public function actionFilterMenu() {
		if(Yii::app()->getRequest()->getPost('filter')){
			$filter=Yii::app()->getRequest()->getPost('filter');
			$criteria = new CDbCriteria();
			$params=array(':id_rest'=>$filter['id_rest']);
			if(isset($filter['category'])){
				$criteria->addCondition('`id_category`=:id');
				$params[':id'] = $filter['category'];
			}
			$criteria->addCondition('`id_restaurant`=:id_rest');
			$criteria->params=$params;
			$data['itemCount'] = Foods::model()->count($criteria);
			$criteria->order = 'title desc';
			if(isset($filter['limit'])) $criteria->limit = $filter['limit'];
			if(isset($filter['offset'])) $criteria->offset = $filter['offset'];
			$data['items'] = Foods::model()->findAll($criteria);
			$this->renderPartial('menu/loaditems',$data);
		}
	}
	public function actionMenu($id)
	{
		$data['rest']=Restaurants::model()->findByPk($id);
		$this->render('menu/catalog', $data);
	}
	public function actionFood($id_rest)
	{
		if (Yii::app()->getRequest()->getQuery('cat')) {
			$data['select_cat'] = Yii::app()->getRequest()->getQuery('cat');
		}
		if(Yii::app()->getRequest()->getQuery('id')){
			$data['item']=Foods::model()->findByPk(Yii::app()->getRequest()->getQuery('id'));
			$data['select_cat'] = $data['item']->id_category;
		}
		$data['rest']=Restaurants::model()->findByPk($id_rest);
		$data['cats']=Category::model()->findAll(array('order'=>'`main` DESC, `filter` DESC, `order` ASC'));
		$this->renderPartial('menu/food', $data);
	}
	public function actionSaveFood()
	{
		if(Yii::app()->getRequest()->getQuery('id') == 'new')
			$record = new Foods();
		else $record = Foods::model()->findByPk(Yii::app()->getRequest()->getQuery('id'));
		$item_record=Yii::app()->getRequest()->getPost('item');
		$record->attributes = $item_record;
		$record->save();
		$this->redirect(CHtml::normalizeUrl(array('catalog/menu', 'id'=>$record->id_restaurant)));
	}

	public function actionDeletedFood($id)
	{
		$deleted=Foods::model()->findByPk($id);
		if(file_exists(YiiBase::getPathOfAlias('webroot').$deleted->img)){
			@unlink(YiiBase::getPathOfAlias('webroot').$deleted->img);
		}
		$deleted->delete();
		$this->redirect(CHtml::normalizeUrl(array('catalog/menu', 'id'=>Yii::app()->getRequest()->getQuery('id_rest'))));
	}
	//endregion

	//region Управление категориями
	public function actionCreateCategory() {
		$data='';
		if(Yii::app()->getRequest()->getQuery('id_rest')){
			$data['rest']=Restaurants::model()->findByPk(Yii::app()->getRequest()->getQuery('id_rest'));
		}
		$data['cats']=Category::model()->findAll(array('order'=>'`main` DESC, `filter` DESC, `order` ASC'));
		$this->renderPartial('category',$data);
	}
	public function actionEditCategory($id) {
		$data['cat'] = Category::model()->findByPk($id);
		if(Yii::app()->getRequest()->getQuery('id_rest')){
			$data['id_rest']=Yii::app()->getRequest()->getQuery('id_rest');
		}
		$this->renderPartial('category', $data);
	}
	public function actionSaveCategory() {
		if(Yii::app()->getRequest()->getQuery('id') == 'new')
			$record = new Category;
		else $record = Category::model()->findByPk(Yii::app()->getRequest()->getQuery('id'));
		$cat_record=Yii::app()->getRequest()->getPost('cat');
		$record->attributes = $cat_record;
		$record->save();
		if (Yii::app()->getRequest()->getPost('id_rest')) {
			$id_rest=Yii::app()->getRequest()->getPost('id_rest');

			if (Yii::app()->getRequest()->getPost('cats')) {
				$cats=Yii::app()->getRequest()->getPost('cats');
				foreach ($cats as $cat) {
					$category = new CategoryRestaurant();
					$category->id_category = $cat;
					$category->id_restaurant = $id_rest;
					$category->save();
				}
			} else {
				$category = new CategoryRestaurant();
				$category->id_category = $record->id;
				$category->id_restaurant = $id_rest;
				$category->save();
			}

			$this->redirect(CHtml::normalizeUrl(array('catalog/menu', 'id'=>$id_rest)));
		} else {
			if (Yii::app()->getRequest()->getQuery('rest_redir')!=0) {
				$this->redirect(CHtml::normalizeUrl(array('catalog/menu', 'id'=>Yii::app()->getRequest()->getQuery('rest_redir'))));
			} else {
				$this->redirect(CHtml::normalizeUrl(array('catalog/')));
			}
		}
	}
	//endregion

	//region Управление Рестораны
	public function actionFilterCatalogItems() {
		if( Yii::app()->getRequest()->getParam('filter') ) {
			$filter = Yii::app()->getRequest()->getParam('filter');
			$criteria = new CDbCriteria();
			if( isset($filter['category']) ) {
				$criteria->addCondition('cid='.(int)$filter['category']);
			}
			$data['itemCount'] = Catalog::model()->count($criteria);
			if( isset($filter['limit']) ) $criteria->limit = $filter['limit'];
			if( isset($filter['offset']) ) $criteria->offset = $filter['offset'];
			$data['items'] = Catalog::model()->findAll($criteria);

			$this->renderPartial('loaditems',$data);
		}
	}
	public function actionRestaurant()
	{
		if(Yii::app()->getRequest()->getQuery('id')){
			$data['item']=Restaurants::model()->findByPk(Yii::app()->getRequest()->getQuery('id'));
		}
		if (Yii::app()->getRequest()->getQuery('rest')) {
			$data['rest']=1;
		}
		$data['cats']=Category::model()->findAll(array('order'=>'`main` DESC, `filter` DESC, `order` ASC'));
		$this->renderPartial('restauran', $data);
	}
	public function actionSaveRestaurant()
	{
		if(Yii::app()->getRequest()->getQuery('id') == 'new')
			$record = new Restaurants();
		else $record = Restaurants::model()->findByPk(Yii::app()->getRequest()->getQuery('id'));
		$item_record=Yii::app()->getRequest()->getPost('item');
		$record->attributes = $item_record;
		$record->time_work=implode('-',Yii::app()->getRequest()->getPost('time'));
		$record->save();
		if(Yii::app()->getRequest()->getPost('cats')){
			$cats=Yii::app()->getRequest()->getPost('cats');
			foreach ($cats as $value) {
				if(!($record->categoryRestaurants(array('condition' => '`id_category`=:id', 'params' => array(':id' => $value)))))
				{
					$cat = new CategoryRestaurant();
					$cat->id_category=$value;
					$cat->id_restaurant=$record->id;
					$cat->save();
				}
			}
			$q=new CDbCriteria();
			$q->addNotInCondition('`id_category`', $cats);
			$q->addCondition('`id_restaurant`='.$record->id.'');
			CategoryRestaurant::model()->deleteAll($q);
		} else{
			CategoryRestaurant::model()->deleteAllByAttributes(array('id_restaurant'=>$record->id));
		}
		if (Yii::app()->getRequest()->getQuery('rest')==1) {
			$this->redirect(CHtml::normalizeUrl(array('catalog/menu', 'id'=>$record->id)));
		} else {
			$this->redirect(CHtml::normalizeUrl(array('catalog/')));

		}
	}

	public function actionDeletedRestaurant($id)
	{
		$deleted=Restaurants::model()->findByPk($id);
		if(file_exists(YiiBase::getPathOfAlias('webroot').$deleted->img)){
			@unlink(YiiBase::getPathOfAlias('webroot').$deleted->img);
		}
		$deleted->delete();
		$this->redirect(CHtml::normalizeUrl(array('catalog/')));

	}
	public function actionRestauranVisible() {
		$id = Yii::app()->getRequest()->getQuery('id');
		$status = Yii::app()->getRequest()->getQuery('status');
		$item = Restaurants::model()->findByPk($id);
		$item->isVisible = $status;
		$item->save();
	}
	//endregion



	//region Управление отзывами AJAX
	public function actionReviews()
	{
			$fields=Yii::app()->getRequest()->getPost('fields');
			$record=Reviews::model()->findByPk(Yii::app()->getRequest()->getPost('id'));
			$record->attributes=$fields;
			$record->save();
			Yii::app()->end();
	}

	public function actionDeletedReviews()
	{
		Reviews::model()->deleteByPk(Yii::app()->getRequest()->getPost('id'));
		Yii::app()->end();
	}
	//endregion

	/*
	 * OLD
	 */

	public function uploadImage($file, $directory) {
		$date = date('YmdHis');
		$i = rand(1, 100000);
		$ext = end(explode(".", $file['name']));
		move_uploaded_file($file['tmp_name'],
			YiiBase::getPathOfAlias('webroot') . "/userfiles/".$directory."/x" . $i .'d'.$date . '.' . $ext);
		return "/userfiles/".$directory."/x" . $i .'d'.$date . '.' . $ext;
	}
	public function actionUploadIcon() {
		foreach ($_FILES as $file) {
			if($file['tmp_name']) {
				echo $this->uploadImage($file, $_GET['f']);
			}
		}
	}
	public function actionUpdateCategoryOrder() {
		$record = Category::model()->findByPk($_GET['id']);
		$record->order = $_GET['order'];
		$record->save();
	}

	public function actionChangeItemVisibility() {
		$id = $_GET['id'];
		$status = $_GET['status'];
		$item = Catalog::model()->findByPk($id);
		$item->isVisible = $status;
		$item->save();
	}
}